var KCE = {
    tabId: null,
    decks: null
}

chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
    switch (request.type) {
        case "init":
            KCE.tabId = sender.tab.id;
            break;
        case "KCE_MSG":
            processMSG(request);
            break;
    }
});

function sendMessage(message, callback) {
    if (KCE.tabId != null) {
        chrome.tabs.sendMessage(KCE.tabId, message, function (response) {
            if (callback) callback(response);
        });
    }
}

function parseResult(svdata) {
    var data = svdata.replace(/[\s\S]*svdata=/, "");
    data = JSON.parse(data);
    return data["api_data"];
}

function processMSG(data) {
    var result = parseResult(data.data);
    if (data.url.indexOf("api_port/port") > -1) {
        processPortMSG(result);
    }
}

function processPortMSG(data) {
    var decks = data["api_deck_port"];
    KCE.decks = decks;
}